<template>
  <nav class="site-navbar" :class="'site-navbar--' + navbarLayoutType">
    <div class="site-navbar__header">
      <h1 class="site-navbar__brand" @click="navigate({ name: 'home' })">
        <a class="site-navbar__brand-lg" href="javascript:">
          供水管网漏损分析系统
        </a>
        <a class="site-navbar__brand-mini" href="javascript:">供水管网</a>
      </h1>
    </div>
    <div class="site-navbar__body clearfix">
      <el-menu class="site-navbar__menu" mode="horizontal">
        <el-menu-item
          class="site-navbar__switch"
          index="0"
          @click="sidebarFold = !sidebarFold"
        >
          <icon-svg name="zhedie" />
        </el-menu-item>
      </el-menu>
      <el-menu
        class="site-navbar__menu site-navbar__menu--right"
        mode="horizontal"
      >
        <!--        <el-menu-item index="1" @click="navigate({ name: 'theme' })">-->
        <!--          <template slot="title">-->
        <!--            <el-badge value="new">-->
        <!--              <icon-svg name="shezhi" class="el-icon-setting" />-->
        <!--            </el-badge>-->
        <!--          </template>-->
        <!--        </el-menu-item>-->
        <!-- <el-menu-item index="2">
          <el-badge value="hot">
            <a href="https://www.renren.io/" target="_blank">官方社区</a>
          </el-badge>
        </el-menu-item>
        <el-submenu index="3">
          <template slot="title">Git源码</template>
          <el-menu-item index="2-1">
            <a
              href="https://github.com/renrenio/renren-fast-vue"
              target="_blank"
            >
              前端
            </a>
          </el-menu-item>
          <el-menu-item index="2-2">
            <a href="https://gitee.com/renrenio/renren-fast" target="_blank">
              后台
            </a>
          </el-menu-item>
          <el-menu-item index="2-3">
            <a
              href="https://gitee.com/renrenio/renren-generator"
              target="_blank"
            >
              代码生成器
            </a>
          </el-menu-item>
        </el-submenu> -->
        <el-menu-item class="site-navbar__avatar" index="3">
          <el-dropdown :show-timeout="0" placement="bottom">
            <span class="el-dropdown-link">
              <img src="../assets/img/avatar.png" :alt="userName" />
              {{ userName }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="updatePasswordHandle()">
                修改密码
              </el-dropdown-item>
              <el-dropdown-item @click.native="logoutHandle()">
                退出
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 弹窗, 修改密码 -->
    <update-password v-if="updatePasswordVisible" ref="updatePassword" />
  </nav>
</template>

<script>
import moment from "moment";
import { clearLoginInfo } from "@/utils";
import UpdatePassword from "./main-navbar-update-password";
import SockJS from "sockjs-client";

export default {
  data() {
    return {
      updatePasswordVisible: false,
      websocket: null,
      wsData: null
    };
  },
  components: {
    UpdatePassword
  },
  computed: {
    navbarLayoutType: {
      get() {
        return this.$store.state.common.navbarLayoutType;
      }
    },
    sidebarFold: {
      get() {
        return this.$store.state.common.sidebarFold;
      },
      set(val) {
        this.$store.commit("common/updateSidebarFold", val);
      }
    },
    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs;
      },
      set(val) {
        this.$store.commit("common/updateMainTabs", val);
      }
    },
    userName: {
      get() {
        return this.$store.state.user.name;
      }
    }
  },
  mounted() {
    this.initWebSocket();
  },
  beforeDestroy() {
    this.onbeforeunload();
  },
  methods: {
    // 修改密码
    updatePasswordHandle() {
      this.updatePasswordVisible = true;
      this.$nextTick(() => {
        this.$refs.updatePassword.init();
      });
    },
    // 退出
    logoutHandle() {
      this.$confirm(`确定进行[退出]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sys/logout"),
            method: "post",
            data: this.$http.adornData()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              clearLoginInfo();
              this.navigate({ name: "login" });
            }
          });
        })
        .catch(() => {});
    },
    initWebSocket() {
      let host = process.env.VUE_APP_API_URL.replace("http", "ws");
      // 判断当前浏览器是否支持WebSocket
      if ("WebSocket" in window) {
        this.websocket = new WebSocket(`${host}/websocket/product`);
      }
      // else {
      //   this.websocket = new SockJS(`${host}/websocket/sockjs`)
      // }

      // 连接错误
      this.websocket.onerror = this.setErrorMessage;

      // 连接成功
      this.websocket.onopen = this.setOnopenMessage;

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage;

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage;

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload;
    },
    setErrorMessage() {
      this.wsData +=
        "WebSocket连接发生错误" + "状态码：" + this.websocket.readyState;
    },
    setOnopenMessage() {
      console.log("WebSocket连接成功" + "状态码：" + this.websocket.readyState);
    },
    setOnmessageMessage(event) {
      if (event && event.data) {
        // console.log(event)
        if (event.data === "pong") {
          console.log("websocket正常连接");
        } else {
          let getData = JSON.parse(event.data);
          if (getData && getData.createTime) {
            console.log(event);
            this.$notify.error({
              title: "报警提示",
              message:
                moment(getData.createTime).format("YYYY-MM-DD HH:mm:ss") +
                "在" +
                getData.flowMeterName +
                "出现报警信息(" +
                getData.description +
                "),请及时进行处理",
              duration: 0
            });
          }

          // let getData = JSON.parse(event.data);
          // if (getData && getData.length && getData.length > 0) {
          //   let ShowData = '';
          //   getData.forEach(item => {
          //     ShowData += "<div style='position: relative;overflow: hidden;'>" +
          //       "<div style='position: relative;overflow: hidden;display: flex;flex-wrap: wrap;'>" +
          //       "<div style='width: 80px;color: #000;font-size: 13px;padding: 0 10px 0 0;text-align:right;'>报警时间:</div>" +
          //       "<div style='flex: 1;color: #666;font-size: 13px;'>" + item.time + "</div>" +
          //       "</div>" +
          //       "<div style='position: relative;overflow: hidden;display: flex;flex-wrap: wrap;'>" +
          //       "<div style='width: 80px;color: #000;font-size: 13px;padding: 0 10px 0 0;text-align:right;'>报警信息:</div>" +
          //       "<div style='flex: 1;color: #f00;font-size: 13px;word-break: break-all;'>" + item.message + "</div>" +
          //       "</div>" +
          //       "</div>"
          //   })
          //   this.$alert(ShowData, '警报信息', {
          //     confirmButtonText: '确定',
          //     dangerouslyUseHTMLString: true
          //   });
          // }
        }
      }
    },
    setOncloseMessage() {
      console.log("WebSocket连接关闭" + "状态码：" + this.websocket.readyState);
    },
    onbeforeunload() {
      this.websocket.close();
    },
    navigate(to) {
      this.$router.push(to).catch(() => {});
    }
  }
};
</script>
